package io.jee.runshan.filter;

import io.jee.medusa.remote.RemoteConnector;
import io.jee.runshan.domain.remote.weixin.Oath2;
import io.jee.runshan.utils.StringUtils;
import io.jee.runshan.utils.WeixinConstant;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WeixinOather2Filter extends BaseFilter {
	private static final Logger logger = LoggerFactory.getLogger(WeixinOather2Filter.class);

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		
		response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
		response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma","No-cache");

		Object openid = session.getAttribute("openid");
		String code = request.getParameter("code");
		
		if (openid == null && StringUtils.notBlank(code)) {
			try {
				String oathPath = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
						+ WeixinConstant.getAppID()
						+ "&secret="
						+ WeixinConstant.getAppSecret()
						+ "&code="
						+ code
						+ "&grant_type=authorization_code";
				Oath2 oath2 = RemoteConnector.get(oathPath, null, Oath2.class);
				session.setAttribute("openid", oath2.getOpenid());
			} catch (Exception e) {

			}
		}
		logger.debug("当前用户Openid：" + session.getAttribute("openid"));
		chain.doFilter(request, response);
	}
	
	public String getRemoteAddress(HttpServletRequest request) {  
        String ip = request.getHeader("x-forwarded-for");  
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {  
            ip = request.getRemoteAddr();  
        }  
        return ip;  
    } 
	
	public String getMACAddress(String ip) {
        String str = "";
        String macAddress = "";
        try {
            Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);  
            InputStreamReader ir = new InputStreamReader(p.getInputStream());  
            LineNumberReader input = new LineNumberReader(ir);  
            for (int i = 1; i < 100; i++) {  
                str = input.readLine();  
                if (str != null) {  
                    if (str.indexOf("MAC Address") > 1) {  
                        macAddress = str.substring(  
                                str.indexOf("MAC Address") + 14, str.length());  
                        break;  
                    }  
                }  
            }  
        } catch (IOException e) {  
            e.printStackTrace(System.out);  
        }  
        return macAddress;  
    }
}
